<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Funds extends REST_Controller {

	private $rdata = array();

    function __construct(){  
        
        parent::__construct();
        $this->returnInfo = lang('returnInfo');
        $this->rdata['returnNo'] = '0000';
        $this->rdata['returnInfo'] = $this->returnInfo['0000'];
        $this->rdata['returnTime'] = time();
        $this->rdata['returnData'] = (object)array();
    }

    protected $rules = array(
        "recharge" => array(
            array(
                'field'   => 'money', 
                'label'   => '充值金额', 
                'rules'   => 'trim|required|numeric|greater_than[100]'
            ),
            array(
                'field'   => 'type', 
                'label'   => '充值方式', 
                'rules'   => 'trim|required|regex_match[/^[01]$/]'
            )
        ),
        "withdraw" => array(
            array(
                'field'   => 'money', 
                'label'   => '提现金额', 
                'rules'   => 'trim|required|numeric|greater_than[100]|callback_withdraw_money_check'
            )
        ),
        "investment" => array(
            array(
                'field'   => 'id', 
                'label'   => '项目ID', 
                'rules'   => 'trim|required|numeric|callback_project_check'
            ),
            array(
                'field'   => 'money', 
                'label'   => '投资金额', 
                'rules'   => 'trim|required|numeric|greater_than[100]|callback_money_check'
            ),
            array(
                'field'   => 'rids', 
                'label'   => '红包', 
                'rules'   => 'trim|callback_rids_check'
            )
        )
    );

    // 用户资产
    public function assets_get () {

    	$key = 'Cache:info:funds:assets:'.$this->uinfo['id'];
    	if (!$data = $this->cache->get($key)) {

    		$this->load->model('interest_model', 'mint', 'default');
    		$this->load->model('red_package_user_model', 'mred');

    		$have_asset       = $this->mint->get_user_asset($this->uinfo['id']);
    		$red_packets      = $this->mred->get_user_red_packets($this->uinfo['id']);
    		$yesterday_income = $this->mint->get_before_income($this->uinfo['id']);
    		$data['money']            = $this->uinfo['money'];
	    	$data['have_asset']       = $have_asset ? $have_asset['money'] : 0;
	    	$data['red_packets']      = $red_packets ? $red_packets['money'] : 0;
	    	$data['yesterday_income'] = $yesterday_income ? $yesterday_income['money'] : 0;
	    	$this->cache->save($key, $data, 60);
    	}
    	$this->rdata['returnData'] = $data;
    	$this->response($this->rdata);
    }

    // 用户充值
    public function recharge_post () {

    	$this->form_validation->set_rules($this->rules['recharge']);
        if ($this->form_validation->run() == FALSE) {
                
            $errs = form_errors();
            $errs_str = '';
            foreach($errs as $key => $value){
                $errs_str .= ' '.$value;
            }
            $this->rdata['returnInfo'] = $errs_str;
            $this->rdata['returnNo'] = '0011';
            $this->response($this->rdata);

        } else {
	    	
	    	$key = 'Cache:lock:funds:recharge:'.$this->uinfo['id'];

	    	if (! $this->uinfo['other_account']) {
	    		
	    		$this->rdata['returnNo']   = '0200';
	    		$this->rdata['returnInfo'] = '用户未认证，请认证后再操作';
	    		$this->response($this->rdata);
	    	}
	    	if (! $this->uinfo['bank_card'] && $this->post('type') == 0) {
	    		
	    		$this->rdata['returnNo']   = '0201';
	    		$this->rdata['returnInfo'] = '用户未绑定银行卡，请绑卡后再操作';
	    		$this->response($this->rdata);
	    	}

	    	if ($this->cache->get($key)) {
	    		
	    		$this->rdata['returnNo']   = '0999';
	    		$this->rdata['returnInfo'] = '用户操作频繁，请稍后操作';
	    		$this->response($this->rdata);
	    	}

	    	$data = array('aid'           => $this->uinfo['id']
	    		        , 'orderid'       => 'CZ'.ordernum_time($this->uinfo['id'])
                        , 'money'         => $this->post('money')
	    		        , 'type'          => $this->post('type')
	    		        , 'other_account' => $this->uinfo['other_account']);

	    	if (!$this->post('type')) {
	    		
	    		$data['bank_card'] = $this->uinfo['bank_card'];
	    	}
	    	$this->load->library('netcredit/loan');

			if ($re = $this->loan->_obj->recharge($data)) {
				
				$returnData['need_jump']   = 1;
				$returnData['go_url']      = $re['url'];
				$this->rdata['returnData'] = $returnData;

				//create pay
				$c_data = array('aid'       => $this->uinfo['id']
					          , 'type'      => $this->post('type')
					          , 'bid'       => intval($this->uinfo['bid'])
					          , 'money'     => $this->post('money')
					          , 'ip'        => get_ip()
					          , 'orderid'   => $data['orderid']
					          , 'create_at' => date('Y-m-d H:i:s'));
				$this->load->model('pay_model', 'mpay', 'default');
				$this->mpay->create($c_data);
				$this->cache->delete($key);
			} else {

				$this->rdata['returnNo']   = '0202';
				$this->rdata['returnInfo'] = '充值失败，发送三方网关失败';
			}
			$this->response($this->rdata);
	    }
    }

    // 用户提现
    public function withdraw_post () {

		$this->form_validation->set_rules($this->rules['withdraw']);
        if ($this->form_validation->run() == FALSE) {
                
            $errs = form_errors();
            $errs_str = '';
            foreach($errs as $key => $value){
                $errs_str .= ' '.$value;
            }
            $this->rdata['returnInfo'] = $errs_str;
            $this->rdata['returnNo'] = '0011';
            $this->response($this->rdata);

        } else {
	    	
	    	$key = 'Cache:lock:funds:withdraw:'.$this->uinfo['id'];

	    	if (! $this->uinfo['other_account']) {
	    		
	    		$this->rdata['returnNo']   = '0200';
	    		$this->rdata['returnInfo'] = '用户未认证，请认证后再操作';
	    		$this->response($this->rdata);
	    	}
	    	if (! $this->uinfo['bank_card']) {
	    		
	    		$this->rdata['returnNo']   = '0201';
	    		$this->rdata['returnInfo'] = '用户未绑定银行卡，请绑卡后再操作';
	    		$this->response($this->rdata);
	    	}

	    	if ($this->cache->get($key)) {
	    		
	    		$this->rdata['returnNo']   = '0999';
	    		$this->rdata['returnInfo'] = '用户操作频繁，请稍后操作';
	    		$this->response($this->rdata);
	    	}

	    	$data = array('aid'           => $this->uinfo['id']
	    		        , 'orderid'       => 'TX'.ordernum_time($this->uinfo['id'])
	    		        , 'money'         => $this->post('money')
	    		        , 'bank_card'     => $this->uinfo['bank_card']
	    		        , 'bank_code'     => $this->uinfo['bank_code']
	    		        , 'province_id'   => $this->uinfo['province_id']
	    		        , 'city_id'       => $this->uinfo['city_id']
	    		        , 'fee'           => 0
	    		        , 'other_account' => $this->uinfo['other_account']);

	    	$this->load->library('netcredit/loan');

			if ($re = $this->loan->_obj->withdraw($data)) {

                //提现时要检查是否是第一次提现 如果是第一次提现 需要更新bankcard表和account中的bid
				
				$returnData['need_jump']   = 1;
				$returnData['go_url']      = $re['url'];
				$this->rdata['returnData'] = $returnData;

				//create withdraw
				$c_data = array('aid'       => $this->uinfo['id']
					          , 'bid'       => intval($this->uinfo['bid'])
					          , 'money'     => $this->post('money')
					          , 'ip'        => get_ip()
					          , 'orderid'   => $data['orderid']
					          , 'create_at' => date('Y-m-d H:i:s'));
				$this->load->model('withdraw_model', 'mwithdraw', 'default');
				$this->mwithdraw->create($c_data);
				$this->cache->delete($key);
			} else {

				$this->rdata['returnNo']   = '0203';
				$this->rdata['returnInfo'] = '提现失败，发送三方网关失败';
			}
			$this->response($this->rdata);
	    }
    }

    // 用户投资
    public function investment_post() {

    	$this->form_validation->set_rules($this->rules['investment']);
        if ($this->form_validation->run() == FALSE) {
                
            $errs = form_errors();
            $errs_str = '';
            foreach($errs as $key => $value){
                $errs_str .= ' '.$value;
            }
            $this->rdata['returnInfo'] = $errs_str;
            $this->rdata['returnNo'] = '0011';

            // 红包解锁
            $rkey = 'Cache:lock:funds:rids:'.$this->uinfo['id'];
            $this->cache->delete($rkey);
            $this->response($this->rdata);

        } else {

        	// Lock
        	$key = 'Cache:lock:funds:investment:'.$this->uinfo['id'];
        	if ($this->cache->get($key)) {
        		
        		$this->rdata['returnInfo'] = '您的操作过于频繁，请稍后操作';
            	$this->rdata['returnNo']   = '0999';
        	} else {

                $this->cache->save($key, time(), 60);
            }

        	$all_red_packages = 0;

        	// 校验红包使用规则
        	if (isset($this->reds)) {
        		
        		foreach ($this->reds as $r) {
        			
        			// 有效期判断
        			if (strtotime($r['expire_at']) && strtotime($r['expire_at']) < time()) {
        				
        				$this->rdata['returnInfo'] = '您使用的红包已过期，投资失败';
        				$this->rdata['returnNo']   = '0204';
        				break;
        			}

        			// 规则判断
        			if ($this->post('money') < $r['require_money']) {
        				
        				$this->rdata['returnInfo'] = '红包抵扣起投金额不得低于'.$r['require_money'].'元，投资失败';
        				$this->rdata['returnNo']   = '0205';
        				break;
        			}

        			if ($this->pinfo['days'] < $r['require_cycle']) {
        				
        				$this->rdata['returnInfo'] = '红包抵扣起投周期不得小于'.$r['require_cycle'].'天，投资失败';
        				$this->rdata['returnNo']   = '0206';
        				break;
        			}
        			$all_red_packages += $r['money'];
        		}
        	}

        	if ($this->rdata['returnNo'] != '0000') {

                //系统验证错误 解锁用户投资
        		$this->cache->delete($key);
        		$this->response($this->rdata);
        	}

            if ($this->pinfo['max_money'] > 0) {

                $mkey = 'Cache:freeze:funds:investment:max_money'.$this->uinfo['id'].'_'.$this->pinfo['id'];

                //最大金额的检查 必须要在成功发送记录之后才存入redis 在存在redis时不可删除 因为当时存在一笔交易请求 而在第一次时 错误就应该删除
                if (!$investment_already = $this->cache->get($mkey)) {

                    //如果redis中没有记录  总投资额从数据库中取 当前的总投资额=历史投资(数据库)+本次提交的投资额
                    $this->load->model("investment_model","minv");
                    $where = array('aid'=>$this->uinfo['id'],"pid"=>$this->pinfo['id']);
                    $fields = "SUM(money) as money";
                    $result = $this->minv->get_one($where,$fields);
                    $investment_already = $result['money'] + $this->post('money');
                }else{

                    //如果redis中有记录 当前的总投资额=历史投资(数据库)+之前提交的没有成功的投资额+本次提交的投资额
                    $investment_already += $this->post('money');
                }


                if ($investment_already > $this->pinfo['max_money']) {

                    //系统验证错误 解锁用户投资
                    $this->cache->delete($key);
                    $this->rdata['returnInfo'] = '您在该项目上的总投资额已经超过上限';
                    $this->rdata['returnNo']   = '0208';
                    $this->response($this->rdata);
                }
                
                //如果这里都验证通过了 那么把当前总投资金额存入redis
                $this->cache->save($mkey,$investment_already,1000);
            }

            //钱多多不接受',' 把他转换成'_'
            $rids_replace = str_replace(',', '_', $this->post('rids'));
        	
        	$data = array('aid'              => $this->uinfo['id']
	    		        , 'orderid'          => 'TZ'.ordernum_time($this->uinfo['id'])
	    		        , 'money'            => $this->post('money')
	    		        , 'full_money'       => $this->pinfo['money']
	    		        , 'pid'              => $this->pinfo['id']
	    		        , 'to_other_account' => $this->pinfo['other_account']
	    		        , 'rids'             => $rids_replace
	    		        , 'red_package'      => $all_red_packages
	    		        , 'other_account'    => $this->uinfo['other_account']);

	    	$this->load->library('netcredit/loan');

			if ($re = $this->loan->_obj->transfer($data)) {
				
				$returnData['need_jump']   = 1;
				$returnData['go_url']      = $re['url'];
				$this->rdata['returnData'] = $returnData;

				//create withdraw
				$c_data = array('aid'       => $this->uinfo['id']
					          , 'pid'       => $this->pinfo['id']
					          , 'money'     => $this->post('money')
					          , 'red_package' => $all_red_packages
					          , 'rids'      => $this->post('rids')
					          , 'orderid'   => $data['orderid']
					          , 'create_at' => date('Y-m-d H:i:s'));

				$fkey = 'Cache:freeze:funds:investment:'.$c_data['orderid'];
				$pkey = 'Cache:freeze:funds:investment:'.$this->pinfo['id'];

				$project_fmoney = $this->cache->get($pkey);
				$project_fmoney = floatval($project_fmoney) + $this->post('money');

				// 有效时间1000s
				$this->cache->save($pkey, $project_fmoney, 60);
				$this->cache->save($fkey, $c_data, 1000);
				$this->cache->delete($key);
			} else {

                //如果没有提交给第三方 那么删除当前投资额的redis
                $this->cache->delete($mkey);
				$this->rdata['returnNo']   = '0207';
				$this->rdata['returnInfo'] = '投资失败，发送三方网关失败';
			}
			$this->response($this->rdata);
        }
    }

    public function pwdValidate_post(){


        if (!$uinfo = $this->session->userdata('UAID')) {

            $this->rdata['returnNo'] = '0013';
            $this->rdata['returnInfo'] = $this->returnInfo['0013'];
            $this->response($this->rdata);
        }


        $id = intval($this->post('id'));
        if (!$id || !is_numeric($id)) {

            $this->rdata['returnNo'] = '0011';
            $this->rdata['returnInfo'] = $this->returnInfo['0011'];
            $this->response($this->rdata);
        }

        $pwd = $this->post('pwd');
        if (!$pwd) {

            $this->rdata['returnNo'] = '0011';
            $this->rdata['returnInfo'] = $this->returnInfo['0011'];
            $this->response($this->rdata);
        }
        
        //如果redis中已经存了验证通过的标记 直接返回
        $pre = 'Cache:Lock:user:pwdValidate_post:'.$uinfo.'_'.$id;
        
        //否则对比密码 用过后标记存入redis
        $this->load->model("project_model","mpro");
        $result = $this->mpro->get_one_id_cache($id);
        if (passwd($pwd) != $result['pwd']) {

            $this->rdata['returnInfo'] = '约标密码错误';
            $this->rdata['returnNo'] = '3311';
        }else{
            
            $this->cache->save($pre,1,86400);
        }
        $this->response($this->rdata);
    }

    /////////////
    ///check/////
    /////////////

    // check project
    public function project_check($id="") {

    	if (!$id) {
    		
    		return FALSE;
    	}
    	$this->load->model('project_model', 'mpro', 'default');
    	$pinfo = $this->mpro->get_one_id_cache($id,FALSE,60);
        $this->pinfo = $pinfo;
    	if (!$pinfo) {
    		
    		$this->form_validation->set_message('project_check', '项目不存在');
    		return FALSE;
    	}
        // 判断新手标
        if ($pinfo['tags']) {

            $this->load->model("investment_model","minv");
            $where = array('aid'=>$this->uinfo['id']);
            if ($this->minv->get_count_all_cache($where) > 0) {
                $this->form_validation->set_message('project_check', '只有第一次投资可以使用新手标');
                return FALSE;
            }
        }

        // 判断新手标
        $start_at = strtotime($pinfo['start_at']);
        if ($start_at && $start_at > time()) {

            $this->form_validation->set_message('project_check', '项目还未开始');
            return FALSE;
        }

        // 判断约标
        if ($pinfo['pwd']) {
            
            $pwd_key = 'Cache:Lock:user:pwdValidate_post:'.$this->uinfo['id'].'_'.$pinfo['id'];
            if (! $this->cache->get($pwd_key)) {

                $this->form_validation->set_message('project_check', '约标项目需要密码验证');
                return FALSE;
            }
            
        }

    	// 判断收款账号
    	if (!$pinfo['other_account']) {
    		
    		$this->form_validation->set_message('project_check', '收款人三方账户标识错误');
    		return FALSE;
    	}

    	// 判断投资条件
    	if ($pinfo['projectstatus'] != 1 || $pinfo['have_money'] >= $pinfo['money']) {
    		
    		$this->form_validation->set_message('project_check', '项目状态过期,投资失败');
    		return FALSE;
    	}

    	// 检查money min
    	if ($this->post('money') < $pinfo['min_money']) {
    		
    		$this->form_validation->set_message('project_check', '投资金额不得低于起投金额'.$pinfo['min_money'].'元');
    		return FALSE;
    	}

    	// 检查money step
    	if (($this->post('money') - $pinfo['min_money']) % $pinfo['step_money']) {
    		
    		$this->form_validation->set_message('project_check', '递增金额必须为'.$pinfo['step_money'].'元');
    		return FALSE;
    	}

    	return TRUE;
    }

    //提现余额检查
    // money project
    public function withdraw_money_check($money) {

            
        if ($this->uinfo['money'] < $money) {
            
            $this->form_validation->set_message('withdraw_money_check', '账户余额不足,投资失败');
            return FALSE;
        }
        return TRUE;
    }

    // money project
    public function money_check($money) {

    	if (isset($this->pinfo)) {
    		
	    	if ($this->uinfo['money'] < $money) {
	    		
	    		$this->form_validation->set_message('money_check', '账户余额不足,投资失败');
	    		return FALSE;
	    	}

    		$have_money  = isset($this->pinfo['have_money']) ? $this->pinfo['have_money'] : 0;
	    	$freeze_money= intval($this->cache->get('Cache:freeze:funds:investment:'.$this->pinfo['id']));
	    	if ($this->pinfo['money'] < ($have_money + $this->post('money') + 0)) {
	    		
	    		$this->form_validation->set_message('money_check', '项目额度不足,投资失败');
	    		return FALSE;
	    	}
	    	return TRUE;
    	} else {

    		$this->form_validation->set_message('money_check', '项目状态异常,投资失败');
	    	return FALSE;
    	}
    }

    // rids project
    public function rids_check($ids="") {

    	if ($ids) {
    		
    		$not_int = 0;
	    	if ($idArr = explode(',', $ids)) {
	    		
	    		foreach ($idArr as $v) {
	    			
	    			if (!intval($v)) {
	    				
	    				$not_int = 1;
	    				break;		
	    			}	
	    		}
	    	}

	    	if ($not_int) {
	    		
	    		$this->form_validation->set_message('rids_check', '红包格式错误,投资失败');
	    		return FALSE;
	    	}

	    	$this->load->model('red_package_user_model', 'mredp', 'default');
	    	$where = array('aid'    => $this->uinfo['id']
	    		         , 'in'     => array('id', $idArr)
	    		         , 'status' => 0);

            $fileds = 'id,money,require_cycle,require_money,expire_at';
	    	$reds = $this->mredp->get_list_where_cache(0,0,FALSE,$where,$fileds);

	    	if (! $reds) {
	    		
	    		$this->form_validation->set_message('rids_check', '无可用红包,投资失败');
	    		return FALSE;
	    	}

	    	// lock red
	    	$key = 'Cache:lock:funds:rids:'.$this->uinfo['id'];
	    	if ($this->cache->get($key)) {
	    		
	    		$this->form_validation->set_message('rids_check', '您的账户还有交易未完成，暂时无法使用红包，请稍后');
	    		return FALSE;
	    	}
	    	$this->cache->save($key, $idArr, 300);
	    	$this->reds = $reds;	
    	}
	    return TRUE;
    }
}